<?php
/***************************************************************************
 *                                install.php
 *                            -------------------
 *   begin                : Tuesday, Apr 21, 2005
 *   copyright            : (C) 2006-2009 Pierre 'pikiou' Scelles
 *   email                : liu.pi.vipi@gmail.com
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   All images, skill names and descriptions are (C) ArenaNet.
 ***************************************************************************/
define('GWBBCODE_ROOT', '.');
require_once(GWBBCODE_ROOT.'/install.inc.php');


//Ask and send an email to gwShack.us
if (isset($_GET['ask_email'])) {
?>
<html><head></head><body><pre><? install_header(); ?>
<script language="JavaScript" type="text/javascript">
//Make sure it looks like an email, then wait 3 seconds and proceed to the installation
//gwShack.us downtime proof
function send_form() {
   var email = document.getElementById('email').value;
   if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email)) {
      alert('This email address is invalid. If you don\'t want to provide one, rather press Skip :p');
      return false;
   }
   if (timer !== false) {
      clearTimeout(timer);
   }
   timer = setTimeout('proceed();', 1000);
   return true;
}
var timer = false;

//Launch the installation
function proceed(skip) {
   var email = skip ? '' : document.getElementById('email').value;
   var new_href = location.href.toString();
   new_href = new_href.replace(/([&?])ask_email=1[&?]?/, '$1');
   new_href = new_href.replace(/\?/, '?email='+encodeURIComponent(email)+'&');
   new_href = new_href.replace(/\&$/, '');
   location.href = new_href;
}
</script>
<form name="shack" method="post" action="http://gwshack.us/email_post.php" target="email_result" onsubmit="send_form();">
All we ask in return for your use of this program is an email to keep you updated on new versions. No spam, no ads.

Email:<input id="email" name="email" type="text" value="" size="50"/> <input name="post" value="Send email" type="submit"/> or <input name="skip" value="Skip" type="button" onclick="proceed(/*skip=*/true);"/> to proceed with the installation.</form>
<iframe name="email_result" border="0" frameborder="0"></iframe>
<div id="loading"></div>
</pre></body></html>
<?
die();
}

//Ask gwShack.us if we need an email
if (!isset($_GET['email'])) {
?>
<html><head>
<script type="text/javascript" src="http://gwshack.us/email.js.php"></script>
</head><body><? install_header(); ?></body></html>
<?
die();
}




//Before we include anything, check config.inc.php
$config_result = '';
if (!isset($_GET['hashes'])) {  //Ignore that part if we're building hashes
   $config = load_config_file(DEFAULT_CONFIG_PATH);
   $config = str_replace("\r", '', $config);
   $old_config = false;
   $first_config = true;
   //Copy settings from the old config to the new one
   if (file_exists(CONFIG_PATH)) {
      $old_config = load_config_file(CONFIG_PATH);
      $prev_config = $old_config;
      $first_config = false;
   }
   else if (file_exists(OLD_CONFIG_PATH)) {
      $old_config = load_config_file(OLD_CONFIG_PATH);
   }
   if ($old_config) {
      //Infuse values from $old_config to $config
      $replacements = Array(
         //"/(?<!//)[^\n/]*" makes sure the define line isn't commented
         "#(?<!//)[^\n/]*define\('USE_GWBBCODE', ([^)]+)\);#" => "define('USE_GWBBCODE', {\$reg[1]});",
         "#(?<!//)[^\n/]*define\('GWBBCODE_SQL', ([^)]+)\);#" => "define('GWBBCODE_SQL', {\$reg[1]});",
         "#(?<!//)[^\n/]*define\('GWBBCODE_ALLEGIANCE', '([^']+)'\);#" => "define('GWBBCODE_ALLEGIANCE', '{\$reg[1]}');",
         "#(?<!//)[^\n/]*define\('GWBBCODE_GAMEPLAY', '([^']+)'\);#" => "define('GWBBCODE_GAMEPLAY', '{\$reg[1]}');",
         "#(?<!//)[^\n/]*define\('GWBBCODE_FASTCASTING_DECIMALS', ([^)]+)\);#" => "define('GWBBCODE_FASTCASTING_DECIMALS', {\$reg[1]});",
         "#(?<!//)[^\n/]*define\('GWBBCODE_WIKI_LINK', '([^']+)'\);#" => "define('GWBBCODE_WIKI_LINK', '{\$reg[1]}');",
         "#\$not_to_hook = (.*)\\);#s" => "\$not_to_hook = {\$reg[1]});",

      );
      foreach ($replacements as $from => $to) {
         if (preg_match($from, $old_config, $reg)) {
            $to = eval('return "'.$to.'";');
            $config = preg_replace($from, $to, $config);
         }
      }
      //Transfer custom defines from $old_config to $config
      $custom_defines = '';
      if (preg_match_all("/(?<!\\/\\/)([^\n\\/]*define\(('[A-Z_]+')[^\r\n]+)/i", $old_config, $regs, PREG_SET_ORDER)) {
         foreach ($regs as $reg) {
            list($all, $line, $constant_name) = $reg;
            if (strpos($config, $constant_name) === false) {
               $custom_defines .= $line."\n";
            }
         }
         $config = preg_replace('#(//Insert custom defines here[^\r\n]+\r?\n)#', "\\0".str_replace('\\', '\\\\', $custom_defines), $config);
      }
   }

   //Save new config only if necessary
   if ($first_config || $prev_config != $config) {
      //Try to save the new config file
      if (($f = @fopen(CONFIG_PATH, 'wb'))
          && ($res = @fwrite($f, $config)) !== false) {
         @fclose($f);
         if (file_exists(OLD_CONFIG_PATH)) {
            rename(OLD_CONFIG_PATH, RENAMED_CONFIG_PATH);
            $config_result = "\n" . basename(OLD_CONFIG_PATH) . ' successfuly copied into ' . basename(CONFIG_PATH) . ', then renamed ' . basename(RENAMED_CONFIG_PATH) . '.';
         }
         else {
            $config_result = "\n" . basename(CONFIG_PATH) . ' successfuly saved. To activate SQL support, set your gameplay (PvP/PvE) and faction allegiance, edit it and refresh this page.';
         }
      }
      else {
         die("<pre>Please save the following lines in ".basename(CONFIG_PATH)." in your gwBBCode directory and restart install.php, \nor rename ".basename(DEFAULT_CONFIG_PATH)." to ".basename(CONFIG_PATH)." and edit it according to the settings you want:<br/><br/>".htmlspecialchars($config)).'</pre>';
      }
   }
}

//PHP-Nuke warm up
if (@file_exists('../../../mainfile.php')){
	define('FORUM_ADMIN', true);
	include('../../../mainfile.php');
	define('IS_NUKE', true);
}

echo '<html><head></head><body><pre>';
install_header();
echo empty($config_result) ? '' : success($config_result);

//Compare and show file md5 hashes mismatching official hashes
echo "\n";
if (!isset($_GET['hashes']) || !file_exists('../../liupishideout.txt')) {
   $version_hashes = require_once(HASHES_PATH);
   compare_hashes(get_hashes(), $version_hashes);
}
//Or save md5 hashes to a new db if we're on the local test server
else {
//TODO: move this hash db creation part to a packaging script
   $hashes = get_hashes();
   $hashes_php = '<'."?php return Array(\n";
   foreach ($hashes as $name => $content) {
      $hashes_php .= "'$name'=>'$content',\n";
   }
   $hashes_php .= ');?'.'>';
   //Save
   if ($f = @fopen(HASHES_PATH, 'wb')) {
      $res = @fwrite($f, $hashes_php);
      @fclose($f);
      die("Hashes saved in ".HASHES_PATH);
   }
}

//Start the installation
$successful = true;
$step = 1;
$forced_software = isset($_GET['forced_software']) ? $_GET['forced_software'] : ''; //Forum software detection bypass

//Check if the pickup database file is writable
$pickup_exists = file_exists(PICKUP_PATH);
$pickup = @load(PICKUP_PATH);
$pickup = is_array($pickup) ? $pickup : Array();
if ($f = @fopen(PICKUP_PATH, 'wb')) {
   @fclose($f);
   if (@save(PICKUP_PATH, $pickup)) {
      if (!$pickup_exists) {
         success(basename(PICKUP_PATH) . " was successfully created and is writable, so the pickup feature will be available.");
      }
   }
   else {
      notice(basename(PICKUP_PATH) . " isn't writable. Please make it writable (chmod 666) and rerun this installation (i.e press F5).\nIf you can't do it, only the pickup feature will be disable.");
   }
}
else {
   notice(basename(PICKUP_PATH) . " doesn't exist. Please create it and rerun this installation (i.e press F5).\nIf you can't do it, only the pickup feature will be disabled.");
}

echo "\nCleaning previous installations...\n";
$successful_cleaning = true;
$successful_cleaning &= rm('dynamic_body.tpl');
$successful_cleaning &= rm('dynamic_header.tpl');
$successful_cleaning &= rm('uninstall.php', true, false);
$successful_cleaning &= rm('functions_gw.php');
$successful_cleaning &= rm('bbcode.tpl');
$successful_cleaning &= rm('skills_php.txt');
$successful_cleaning &= rm('skill_names.txt');
$successful_cleaning &= rm('overall_header.tpl');
$successful_cleaning &= rm('overall_body.tpl');
$successful_cleaning &= rm('checkup.php');
if ($successful_cleaning) {
   success("Done.");
}
echo "\n";

//phpBB 3.0
if (   $forced_software == 'phpBB3'
    || (file_exists(GWBBCODE_ROOT.'/../index.php') && strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'phpBB3') !== false)) {
   if (GWBBCODE_SQL) {
      define('IN_PHPBB', true);
      $phpbb_root_path = './../';
      $phpEx = substr(strrchr(__FILE__, '.'), 1);
      require($phpbb_root_path . 'common.' . $phpEx);
      require($phpbb_root_path . 'config.' . $phpEx);
   }

   //Installing, at last
   echo "\nHooking phpBB3...\n";
   add_to_file($step++, "// Additional tables",
               "define('GWBBCODE_ROOT', \"{\$phpbb_root_path}gwbbcode\");",
               GWBBCODE_ROOT.'/../includes/constants.php');
   add_to_file($step++, "		\$message = str_replace(':' . \$this->bbcode_uid, '', \$message);",
               "include(GWBBCODE_ROOT.'/gwbbcode.php');",
               GWBBCODE_ROOT.'/../includes/bbcode.php');
   add_to_file($step++, "	\$s_first_unread = false;",
               "include(GWBBCODE_ROOT.'/gwbbcode.php');",
               GWBBCODE_ROOT.'/../viewtopic.php');

   //Recreate and fill the skills table
   if (GWBBCODE_SQL) {
      echo "\n\nPreparing the MySQL skill table...\n";
      add_skills_to_sql();
   }
}



//phpBB2 & PHP-Nuke
else if (   ($forced_software == 'phpBB2' || $forced_software == 'PHP-Nuke')
         || (   file_exists(GWBBCODE_ROOT.'/../index.php')
             && (   strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'phpBB') !== false
                 || strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'JOOM_PHPBB') !== false))) {
   if (GWBBCODE_SQL) {
      error_reporting(0);  //Otherwise it shows a warning about headers being sent already
      define('IN_PHPBB', true);
      define('IN_ADMIN', true);
      $no_page_header = TRUE;
      $phpbb_root_path = './../';
      require($phpbb_root_path . 'extension.inc');
      include($phpbb_root_path . 'common.'.$phpEx);
      error_reporting(E_ALL);
   }

   //PHP-Nuke
	define('GWBB_ROOT', (defined('IS_NUKE') ? 'modules/Forums/' : ''));
	define('INCL_ROOT', (defined('IS_NUKE') ? '../../../' : GWBBCODE_ROOT.'/../'));

   //Cleaning from previous gwBBCode versions
   echo "\nCleaning phpBB2 from previous versions...\n";
   sub_from_file($step++, "// Remove our padding from the string..\n\t\$text = substr(\$text, 1);",
               "include_once('".GWBB_ROOT."gwbbcode/functions_gw.php');",
               INCL_ROOT.'includes/bbcode.php');
   sub_from_file($step++, "'T_SPAN_CLASS3' => \$theme['span_class3'],",
               "   'GWBBCODE_HEAD' => file_get_contents('".GWBB_ROOT."gwbbcode/overall_header.tpl'),",
               INCL_ROOT.'includes/page_header.php');
   sub_from_file($step++, "'T_SPAN_CLASS3' => \$theme['span_class3'],",
               "@\\n[ \t]+'GWBBCODE_HEAD' => include\\('gwbbcode/header\\.php'\\), *@",
               INCL_ROOT.'includes/page_header.php',
               true);
   sub_from_file($step++, "'T_SPAN_CLASS3' => \$theme['span_class3'],",
               "@\\n[ \t]+'GWBBCODE_BODY' => include\\('gwbbcode/body\\.php'\\), *@",
               INCL_ROOT.'includes/page_header.php',
               true);
   if (file_exists(OLD_PICKUP_PATH)) {
      $pickup = eval('return '.file_get_contents(OLD_PICKUP_PATH).';');
      if (save(PICKUP_PATH, $pickup)) {
         echo 'Transfering ' . OLD_PICKUP_PATH . ' to ' . PICKUP_PATH . ': ' . success('done', true);
         rm(OLD_PICKUP_PATH, false);
      }
   }
      
   //Installing
   echo "\nHooking phpBB2...\n";
   add_to_file($step++, "// Remove our padding from the string..\n\t\$text = substr(\$text, 1);",
               "include('".GWBB_ROOT."gwbbcode/gwbbcode.php');",
               INCL_ROOT.'includes/bbcode.php');
   
   //Recreate and fill the skills table
   if (GWBBCODE_SQL) {
      echo "\n\nPreparing the MySQL skill table...\n";
      add_skills_to_sql();
   }
}



//vBulletin
//TODO
else if (   $forced_software == 'vBulletin'
         || (file_exists(GWBBCODE_ROOT.'/../index.php') && strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'vBulletin') !== false)) {
   echo "\nHooking vBulletin...\n";
   add_to_file($step++, "function parse_bbcode(\$input_text, \$do_smilies, \$do_html = false)\n\t{",
               "include('gwbbcode/gwbbcode.php');\n\$input_text = parse_gwbbcode(\$input_text);",
               GWBBCODE_ROOT.'/../includes/class_bbcode.php');
   if (GWBBCODE_SQL) {
      failure('SQL isn\'t supported on vBulletin! Please disable by editing '.basename(CONFIG_PATH));
   }
   echo "\nYou need to change the number of images allowed in a post otherwise gwBBCode's images won't show :(";
   echo "\nTo do that, go to vBulletin Options/Message Posting and Editing Options and change Maximum Images Per Post";
}




//PunBB
else if (   $forced_software == 'PunBB'
         || (file_exists(GWBBCODE_ROOT.'/../index.php') && strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'PunBB') !== false)) {
   echo "\nHooking PunBB...\n";
   add_to_file($step++, '$text = preg_replace($pattern, $replace, $text);',
               "include('gwbbcode/gwbbcode.php');",
               GWBBCODE_ROOT.'/../include/parser.php');
   if (GWBBCODE_SQL) {
      failure('SQL isn\'t supported on PunBB! Please disable by editing '.basename(CONFIG_PATH));
   }
}


//MyBB
else if (   $forced_software == 'MyBB'
         || (file_exists(GWBBCODE_ROOT.'/../index.php') && strpos(file_get_contents(GWBBCODE_ROOT.'/../index.php'), 'MyBB') !== false)) {
   echo "\nHooking MyBB...\n";
   add_to_file($step++, '$message = $this->mycode_parse_quotes($message);',
               "\t\tinclude('gwbbcode/gwbbcode.php');\n\t\t\$message = parse_gwbbcode(\$message);",
               GWBBCODE_ROOT.'/../inc/class_parser.php');
   if (GWBBCODE_SQL) {
      failure('SQL isn\'t supported on MyBB! Please disable by editing '.basename(CONFIG_PATH));
   }
}


else {
   failure('No supported software on which to hook gwBBCode was found :\'(');
   //Propose to bypass forum software check
   echo 'If there is a forum software you want to force installation on, click it: ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=phpBB3">phpBB3</a>, ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=phpBB2">phpBB2</a>, ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=vBulletin">vBulletin</a>, ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=PunBB">PunBB</a>, ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=MyBB">MyBB</a>, ';
   echo '<a href="?email='.rawurlencode($_GET['email']).'&forced_software=PHP-Nuke">PHP-Nuke</a>.' . "\n";
}


echo "\n\n";
if ($successful)
   success('! Installation successfully completed !');
else
   failure('Installation failed!');
   echo 'If you can\'t resolve the issue(s), please visit <a href="http://gwshack.us/forums/viewforum.php?f=2">gwBBCode\'s forums</a> and post about it (no registration needed).';
?>

<form name="shack" method="post" action="http://gwshack.us/email_post.php" target="form_result">
<br/>The email you gave me is <?= htmlentities($_GET['email'])."\n" ?>
If you want to use another one instead:
<input name="email" type="text" value="" size="50"/> <input name="post" value="Send email" type="submit"/></form>
<iframe name="form_result" border="0" frameborder="0"></iframe>
</pre></body></html>